import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  FlatList,
  Image,
  ActivityIndicator,
} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import AreaView from '../../components/Layout/AreaView';
import styles from './style';
import Tabs from '../../components/Tabs';
import SearchHeadIcon from '../../components/SearchHeadIcon';
import BaseUrl from '../../config/BaseUrl';
import {getOrderList, delOrder} from '../../service/my';

const ps = 10;

const MyOrder = (props) => {
  const navigation = useNavigation();
  const [orderStatus, setOrderStatus] = useState();
  const [orderList, setOrderList] = useState([]);
  const [refreshing, setRefreshing] = React.useState(false);
  const [total, setTotal] = React.useState(0);
  const [pn, setPn] = useState(1);
  const {
    route: {
      params: {custId},
    },
  } = props;
  useEffect(() => {
    navigation.setOptions({
      title: '我的订单',
      // headerRight: () => <SearchHeadIcon />,
    });
  }, [navigation]);
  const dataSource = [
    {name: '全部', id: 0},
    {name: '待付款', id: 1, orderStatus: 0},
    {name: '已完成', id: 2, orderStatus: 1},
    {name: '已取消', id: 3, orderStatus: 3},
  ];
  const onChange = (val) => {
    console.log(val);
    setOrderStatus(val.orderStatus);
    setOrderList([]);
    setPn(1);
  };
  const init = () => {
    getOrderList({custId, orderStatus, ps: 10, pn}).then((res) => {
      console.log(res);
      setTotal(res.total || 0);
      let _list = orderList;
      if (pn * 1 !== 1) {
        _list = _list.concat(res.rows);
      } else {
        _list = res.rows;
        setRefreshing(false);
      }
      setOrderList(_list || []);
    });
  };
  useEffect(() => {
    init();
  }, [pn, orderStatus]);

  const onEndReached = () => {
    if (pn * 10 > total) {
      return false;
    }
    const num = pn + 1;
    setPn(num);
  };
  const renderItem = ({item}) => {
    return (
      <>
        {item.smOrderCmCourseList.length > 0 && (
          <TouchableOpacity  activeOpacity={1} activeOpacity={1}>
            {(item.smOrderCmCourseList || []).map((itm) => (
              <TouchableOpacity
                onPress={() => {
                  navigation.push('OrderDetail', {orderId: item.orderId});
                }}
                activeOpacity={1}
                style={styles.list}>
                <View style={styles.video}>
                  <Image
                    source={{uri: BaseUrl.imgurl + itm?.courseImage}}
                    style={styles.cover}
                  />
                  <Image
                    source={require('../../assets/images/video_stop.png')}
                    style={styles.icon}
                  />
                </View>
                <View style={styles.info}>
                  <View style={styles.title_container}>
                    <Text numberOfLines={1} style={styles.title}>
                      {itm?.courseTitle}
                    </Text>
                    {/* <Image
                            style={styles.del_icon}
                            source={require('../../assets/images/del.png')}
                          /> */}
                  </View>
                  <Text numberOfLines={1} style={styles.time}>
                    {itm?.courseIntr}
                  </Text>
                  <Text style={styles.money}>￥{itm?.cmCourseActualPrice}</Text>
                </View>
              </TouchableOpacity>
            ))}
            {item?.orderTtatus === '0' && (
              <View style={styles.action}>
                <Text style={styles.text_time}>
                  {/* 请在23小时2分钟21秒内完成支付 */}
                </Text>
                <TouchableOpacity
                  style={styles.btn}
                  onPress={() =>
                    navigation.push('ResetPay', {
                      orderId: item.orderId,
                    })
                  }>
                  <Text style={styles.btn_text_shop}>待支付</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.btn}
                  onPress={() =>
                    delOrder({orderId: item.orderId}).then((res) => {
                      init();
                    })
                  }>
                  <Text style={styles.btn_text_shop}>取消订单</Text>
                </TouchableOpacity>
              </View>
            )}
            {item?.orderTtatus === '1' && (
              <View style={styles.action}>
                {/* <TouchableOpacity  activeOpacity={1} style={styles.btn}>
                  <Text style={styles.btn_text}>删除课程</Text>
                </TouchableOpacity> */}
                <TouchableOpacity
                  style={styles.btn}
                  onPress={(e) => {
                    e.preventDefault();
                    navigation.push('InvoiceDetail', {
                      orderId: item.orderId,
                    });
                  }}>
                  <Text style={styles.btn_text}>查看发票</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.btn}
                  onPress={(e) => {
                    e.preventDefault();
                    navigation.push('SaleAfter', {
                      orderId: item.orderId,
                    });
                  }}>
                  <Text style={styles.btn_text}>退换/售后</Text>
                </TouchableOpacity>
                {/* <TouchableOpacity
                  style={styles.btn}
                  onPress={(e) => {
                    e.preventDefault();
                    navigation.push('ResetPay', {
                      orderId: item.orderId,
                    });
                  }}>
                  <Text style={styles.btn_text_shop}>再次购买</Text>
                </TouchableOpacity> */}
              </View>
            )}
            {item?.orderTtatus === '3' && (
              <View style={styles.action}>
                <TouchableOpacity
                  style={styles.btn}
                  onPress={(e) => {
                    e.preventDefault();
                    navigation.push('ResetPay', {
                      orderId: item.orderId,
                    });
                  }}>
                  <Text style={styles.btn_text_shop}>再次购买</Text>
                </TouchableOpacity>
              </View>
            )}
          </TouchableOpacity>
        )}
      </>
    );
  };
  return (
    <AreaView>
      <View style={styles.box}>
        <Tabs dataSource={dataSource} onChange={onChange} />
        <FlatList
          style={styles.container}
          refreshing={refreshing}
          showsVerticalScrollIndicator={false}
          data={[...orderList]}
          renderItem={renderItem}
          keyExtractor={(item, index) => item.orderId + index + item}
          onEndReachedThreshold={0.2}
          onEndReached={onEndReached}
          ListFooterComponent={() => (
            <View style={styles.footer_loading}>
              {!(ps * pn > (total || 10)) && (
                <ActivityIndicator
                  animating={true}
                  color="#666"
                  text="数据加载中......"
                />
              )}
            </View>
          )}
        />
      </View>
    </AreaView>
  );
};

export default MyOrder;
